package com.zh.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.zh.model.User;
import com.zh.service.UserService;
import com.zh.service.impl.UserServiceImpl;

@WebServlet("/user")
public class UserServlet extends HttpServlet{

	private UserService UserService = new UserServiceImpl();
	
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		PrintWriter print = resp.getWriter();
		String flag = req.getParameter("flag");
	//获取所有的参数，转换成map对象
		Map params = req.getParameterMap();
		//获取标识（用于判断新增，修改，删除，查询操作）
		User user = new User();
		try {
			//把参数转出user对象
			BeanUtils.populate(user, params);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		//新增
		if(flag.equals("add")) {
			UserService.add(user);
		}else if(flag.equals("mod")) {
//			修改
			UserService.mod(user);
		}else if(flag.equals("del")) {
//			删除
			UserService.del(user.getId());
		}else if(flag.equals("query")){
			List<User> lists = UserService.query(user);
			print.write(lists.toString());
			return;
		}
		
		print.write("success222222222222222222");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req,resp);
	}
	
	
	
}
